<template>
  <div>
    <el-form
      ref="ruleFormRef"
      v-model="form"
      size="large"
      :rules="rules"
      status-icon
      label-position="right"
      label-width="7em"
    >
      <div class="up">
        <div class="up-left">
          <el-form-item
            label="昵称"
            prop="name"
          >
            <el-input
              v-model="form.name"
              autocomplete="new-password"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.sex">
              <el-radio value="男">男</el-radio>
              <el-radio value="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="up-right">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                alt=""
              />
              <el-icon
                v-else
                class="avatar-uploader-icon"
              >
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
      </div>
      <div class="down">
        <el-form-item label="原密码">
          <el-input
            v-model="form.oldPassword"
            type="password"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="form.password"
            type="password"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="checkPassword"
        >
          <el-input
            v-model="form.checkPassword"
            type="password"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item class="btn">
          <el-button
            type="primary"
            @click="onSubmit"
            >提交并修改
          </el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const imageUrl = ref('')
const ruleFormRef = ref<FormInstance>()
const form = reactive({
  name: '',
  sex: '',
  avatar: '',
  oldPassword: '',
  password: '',
  checkPassword: '',
  email: '',
})

const validatePass = (_rule: any, _value: any, callback: any) => {
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,20}$/
  if (form.password.trim() === '') {
    callback(new Error('请输入密码'))
  } else if (!passwordRegex.test(form.password)) {
    callback(
      new Error(
        '密码长度在 8 到 20 个字符之间。 至少包含一个大写字母。 至少包含一个小写字母。 至少包含一个数字。\n 至少包含一个特殊字符（例如：!@#$%^&*）。 不允许包含空格。'
      )
    )
  } else {
    if (form.checkPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (_rule: any, _value: any, callback: any) => {
  if (form.checkPassword === '') {
    callback(new Error('请重新输入'))
  } else if (form.checkPassword !== form.password) {
    callback(new Error('两次输入不一致'))
  } else {
    callback()
  }
}
const validateName = (_rule: any, _value: any, callback: any) => {
  if (form.name === undefined || form.name.trim() === '') {
    callback(new Error('请输入昵称'))
  } else {
    callback()
  }
}
const validateEmail = (_rule: any, _value: any, callback: any) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (form.email === undefined || form.email.trim() === '') {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(form.email)) {
    callback(new Error('邮箱格式不正确'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof form>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  checkPassword: [{ validator: validatePass2, trigger: 'blur' }],
  name: [{ validator: validateName, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
})

const handleAvatarSuccess: UploadProps['onSuccess'] = uploadFile => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG/PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const onSubmit = () => {}
</script>

<style scoped>
.up {
  display: flex;
  margin-top: 2em;
}

.up-left {
  width: 50%;
  margin: 2em 0 0 2em;
}

.up-right {
  margin-left: 1em;
  margin-top: 1em;
}

.up-right .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.down {
  width: 70%;
  margin: 2em auto;
}

.down .el-form-item {
  margin-bottom: 2em;
}

.down .el-input {
  width: 30em;
}

.down .btn {
  text-align: center;
  display: flex;
  justify-content: flex-end;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
